package com.yangming.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yangming.common.base.BaseController;
import com.yangming.common.base.BaseResponseEnum;
import com.yangming.common.base.SystemProperties;
import com.yangming.common.utils.BackJsonBeanUtil;
import com.yangming.common.utils.RequestUtil;
import com.yangming.common.utils.SpringUtil;
import com.yangming.common.wxpay.WXPayException;
import com.yangming.common.wxpay.WXUtil;
import com.yangming.model.Records;
import com.yangming.service.IPayService;
import com.yangming.service.IRecordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 支付Controller
 *
 * @author PengShuiMing
 * @create 2018-09-10
 **/
@RequestMapping("/pay")
@RestController
public class PayController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(PayController.class);
    @Autowired
    private WxPayConfig payConfig;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IPayService payService;
    @Autowired
    private IRecordsService recordsService;
    /**
     * @param outTradeNo   商户订单号（必填）
     * @param orderSubject 订单名称（必填）
     * @param supplyId     货源id（必填）
     * @param serviceId    空板车服务id（必填）
     *                     微信公众号支付接口，通过参数生成网页微信js支付参数，掉起支付界面必须参数
     */
    @RequestMapping("/toPayInfo.json")
    public Object getJSSDKPayInfo(String outTradeNo, String orderSubject, Integer supplyId, Integer serviceId) {
        BaseResponseEnum baseResponseEnum = BaseResponseEnum.ERROR;
        WxPayMpOrderResult wxPayMpOrderResult = null;
        try {
            String openId = this.getOpenId();
            //获取配置文件
            WxPayUnifiedOrderRequest prepayInfo = WxPayUnifiedOrderRequest.newBuilder()
                    .openid(openId)//用户标识
                    .body(orderSubject)//商品描述
                    .outTradeNo(outTradeNo)//商户订单号
                    .notifyUrl(SpringUtil.getBeanByClass(SystemProperties.class).getServerPath() + WXUtil.NOTIFY_URL)//回调地址
                    .tradeType(WXUtil.TRADE_TYPE)//公众号支付
                    .spbillCreateIp(RequestUtil.getIpAddr(request))
                    .build();
            wxPayMpOrderResult = payService.weChatCreateOrder(prepayInfo, supplyId, serviceId);
            baseResponseEnum = BaseResponseEnum.SUCCESS;
        } catch (WXPayException e) {
            logger.error("[微信公众号支付接口]",e.getMessage(),e);
            return BackJsonBeanUtil.getBackJsonBean(BaseResponseEnum.ERROR_PAY,e.getMessage());
        }catch (Exception e){
            logger.error("[微信公众号支付接口]",e.getMessage(),e);
        }
        return BackJsonBeanUtil.getBackJsonBean(baseResponseEnum,wxPayMpOrderResult);
    }

    /**
     * 微信支付回调
     * @param xmlData
     * @return
     * @throws WxPayException
     */
    @PostMapping("/notifyCallback")
    public String parseOrderNotifyResult(@RequestBody String xmlData)  {
        String result = WxPayNotifyResponse.success("支付成功!");
        try {
            WxPayOrderNotifyResult wxPayOrderNotifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            if(WxPayConstants.ResultCode.SUCCESS.equals(wxPayOrderNotifyResult.getResultCode())){
                String outTradeNo = wxPayOrderNotifyResult.getOutTradeNo();//订单号
                Records records = recordsService.selectByOrderNo(outTradeNo);
                if (null == records){
                    throw new Exception("订单号异常!");
                }
                records.setIsPay(1);//已支付
                String transactionId = wxPayOrderNotifyResult.getTransactionId();//微信订单号
                records.setTransactionId(transactionId);
                recordsService.updateById(records);
            }else {
                result = WxPayNotifyResponse.fail("支付失败!");
            }
        } catch (Exception e) {
            result = WxPayNotifyResponse.fail(e.getMessage());
            logger.error("[微信公众号支付回调]",e.getMessage(),e);
        }
        return result;
    }
}
